import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gluz/app/data/shop/shop_cart_entity.dart';

import '../../../../../app_session.dart';

/// 购物车控制器
class CartController extends GetxController with GetTickerProviderStateMixin {
  // 购物车商品列表
  final RxList<ShopCartEntity> cartList = <ShopCartEntity>[].obs;

  // 商家列表
  final RxList<String> storeList = <String>[].obs;

  // 当前选中的商家索引
  final RxInt selectedStoreIndex = 0.obs;

  // Tab控制器
  late TabController tabController;

  // 是否全选
  final RxBool isAllSelected = false.obs;

  // 合计价格
  final RxDouble totalPrice = 0.0.obs;

  // 选中商品数量
  final RxInt selectedCount = 0.obs;

  @override
  void onInit() {
    super.onInit();
    _loadProductCartList();
  }

  @override
  void onClose() {
    tabController.dispose();
    super.onClose();
  }

  // 获取购物车列表
  Future<void> _loadProductCartList() async {
    cartList.value =
        await app.http.request(
          path: '/api/carriage/shoppingCartList',
          params: {'pageSize': 100, 'pageNum': 0},
          fromJson: (e) {
            List listMap = e['records'];
            return listMap.map((obj) {
              return ShopCartEntity.fromJson(Map<String, dynamic>.from(obj));
            }).toList();
          },
        ) ??
        [];
    // 提取商家列表
    final stores = cartList.map((item) => item.merchantName).toSet().toList();
    storeList.value = stores;

    // 初始化Tab控制器
    tabController = TabController(length: stores.length, vsync: this);
    tabController.addListener(_onTabChanged);

    _updateTotalPrice();
  }

  /// Tab切换监听
  void _onTabChanged() {
    selectedStoreIndex.value = tabController.index;
  }

  /// 切换商家
  void switchStore(int index) {
    tabController.animateTo(index);
  }

  /// 获取当前商家下的商品
  List<ShopCartEntity> getCurrentStoreItems() {
    if (storeList.isEmpty) return [];
    final currentStore = storeList[selectedStoreIndex.value];
    return cartList.where((item) => item.merchantName == currentStore).toList();
  }

  /// 切换商品选中状态
  void toggleItemSelection(String itemId) {
    final index = cartList.indexWhere((item) => item.id == itemId);
    if (index != -1) {
      cartList[index] = cartList[index].copyWith(
        isSelected: !cartList[index].isSelected,
      );
      cartList.refresh();
      _updateTotalPrice();
      _updateAllSelectedStatus();
    }
  }

  /// 全选/取消全选
  void toggleAllSelection() {
    final newSelectionState = !isAllSelected.value;

    for (int i = 0; i < cartList.length; i++) {
      if (cartList[i].merchantName == storeList[selectedStoreIndex.value]) {
        cartList[i] = cartList[i].copyWith(isSelected: newSelectionState);
      }
    }
    cartList.refresh();
    _updateTotalPrice();
    _updateAllSelectedStatus();
  }

  /// 更新全选状态
  void _updateAllSelectedStatus() {
    final currentItems = getCurrentStoreItems();
    if (currentItems.isEmpty) {
      isAllSelected.value = false;
      return;
    }

    final selectedItems = currentItems.where((item) => item.isSelected).length;
    isAllSelected.value = selectedItems == currentItems.length;
  }

  /// 更新合计价格
  void _updateTotalPrice() {
    final currentItems = getCurrentStoreItems();
    final selectedItems = currentItems.where((item) => item.isSelected);

    totalPrice.value = selectedItems.fold(
      0.0,
      (sum, item) => sum + (item.unitPrice * item.quantity),
    );
    selectedCount.value = selectedItems.length;
  }

  /// 增加商品数量
  void increaseQuantity(String itemId) {
    final index = cartList.indexWhere((item) => item.id == itemId);
    if (index != -1) {
      cartList[index] = cartList[index].copyWith(
        quantity: cartList[index].quantity + 1,
      );
      cartList.refresh();
      _updateTotalPrice();
    }
  }

  /// 减少商品数量
  void decreaseQuantity(String itemId) {
    final index = cartList.indexWhere((item) => item.id == itemId);
    if (index != -1 && cartList[index].quantity > 1) {
      cartList[index] = cartList[index].copyWith(
        quantity: cartList[index].quantity - 1,
      );
      cartList.refresh();
      _updateTotalPrice();
    }
  }

  /// 移入收藏
  void moveToFavorites(String itemId) {
    // TODO: 实现移入收藏逻辑
    Get.snackbar('提示', '商品已移入收藏');
  }

  /// 删除商品
  void removeItem(String itemId) {
    cartList.removeWhere((item) => item.id == itemId);
    _updateTotalPrice();
    _updateAllSelectedStatus();
    Get.snackbar('提示', '商品已删除');
  }

  /// 结算
  void checkout() {
    final selectedItems = cartList.where((item) => item.isSelected).toList();
    if (selectedItems.isEmpty) {
      Get.snackbar('提示', '请选择要结算的商品');
      return;
    }

    // TODO: 跳转到订单确认页面
    Get.snackbar('提示', '跳转到订单确认页面');
  }

  /// 返回
  void goBack() {
    Get.back();
  }
}
